package com.weiyi.mashangzhu.easemob.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;

import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.util.EasyUtils;
import com.squareup.okhttp.Request;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.ProgressDialog;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.easemob.db.ChatDao;
import com.weiyi.mashangzhu.easemob.runtimepermissions.PermissionsManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

public class ChatActivity extends BaseActivity {
    public static ChatActivity activityInstance;
    private EaseChatFragment chatFragment;
    String toChatUsername;
    private String firstChat;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.em_activity_chat);
        LoadingDialog.dismiss(ChatActivity.this);
        activityInstance = this;
        //get user id or group id
        toChatUsername = getIntent().getExtras().getString("userId");
        firstChat = getIntent().getExtras().getString("firstChat");
        //use EaseChatFratFragment
        chatFragment = new ChatFragment();
        //pass parameters to chat fragment
        chatFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commit();

        if (toChatUsername != null) {
            String leftNick = "";
            String leftHead = "";
            String rightHead = "";
            ChatDao chatDao = new ChatDao(this);
            String[] leftAccount = chatDao.findByAccount(toChatUsername);
            String token = SPUtils.get(this, "token", "") + "";
            String[] split = token.split("@");
            if (split.length > 1) {
                String userAccount = split[1];
                if (userAccount != null) {
                    String[] rightAccount = chatDao.findByAccount(userAccount);
                    if (rightAccount != null && rightAccount.length > 0) {
                        rightHead = rightAccount[1];
                    }
                }
            }
            if (leftAccount != null && leftAccount.length > 0) {
                leftNick = leftAccount[0];
                leftHead = leftAccount[1];
            }
            chatFragment.setChatInfo(leftNick, leftHead, rightHead);

            if (!"1".equals(firstChat)) {
                initNickAndHead(toChatUsername);
            }
        }
    }

    private void initNickAndHead(final String id) {
        OkHttpUtils.get().addParams("id", id).url(API.BaseApi_R + API.findHeadandName).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("status") == 0) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        String uNickname = jsonObject1.getString("uNickname");
                        String uHead = jsonObject1.getString("uHead");
                        saveNickAndAvatar(id, uNickname, uHead);
                    }
                } catch (JSONException e) {

                }
            }
        });
    }

    private void saveNickAndAvatar(String userAccount, String uNickname, String uHead) {
        ChatDao chatDao = new ChatDao(this);
        if (!chatDao.isExist(userAccount)) {
            chatDao.add(userAccount, uNickname, uHead);
        } else {
            chatDao.update(userAccount, uNickname, uHead);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
    	// make sure only one chat activity is opened
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }
    
    @Override
    public void onBackPressed() {
        chatFragment.onBackPressed();
        if (EasyUtils.isSingleActivity(this)) {
//            Intent intent = new Intent(this, MainActivity.class);
//            startActivity(intent);
            finish();
        }
    }
    
    public String getToChatUsername(){
        return toChatUsername;
    }

    @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }
}
